<?php

/**
 * 路由类
 */

namespace variant\core;

class Route {

	/**
	 * 路由开关
	 * @var boolean
	 */
	static protected $rewriteOn = false;

	/**
	 * 解析URL
	 * @param  boolean $rewriteOn   路由开关
	 * @return void
	 */
	static public function init($rewriteOn=false) {
		self::$rewriteOn = $rewriteOn;

		//获取URL
		$indexName = trim($_SERVER["SCRIPT_NAME"],'/');
		$extName = config('ROUTE.REWRITE_SUFFIX');
		$urlPath = parse_url(SELF_URL);
		$urlPath = trim($urlPath['path'],'/');

		//去除入口目录
		if(stripos($urlPath, $indexName, 0) !== false){
			$urlPath = substr($urlPath, strlen($indexName) + 1);
		}
		//去除后缀
		if(strripos($urlPath, $extName, 0) !== false){
			$urlPath = substr($urlPath, 0, -strlen($extName));
		}
		//解析动作
		$routeArr = explode("/", $urlPath, 4);
		$app_name = empty($routeArr[0]) ? config('ROUTE.DEFAULT_APP') : $routeArr[0];
		$controller_name = empty($routeArr[1]) ? config('ROUTE.DEFAULT_CONTROLLER') : $routeArr[1];
		$action_name = empty($routeArr[2]) ? config('ROUTE.DEFAULT_ACTION') : $routeArr[2];

		if( !defined('APP_NAME') ) define('APP_NAME', strtolower($app_name));
		if( !defined('CONTROLLER_NAME') ) define('CONTROLLER_NAME', ucfirst($controller_name));
		if( !defined('ACTION_NAME') ) define('ACTION_NAME', $action_name);

		//解析参数
		if(empty($routeArr[3])) return;
		$paramArray = explode("/", $routeArr[3]);
		foreach ($paramArray as $key => $value) {
			$list = explode('-',$value,2);
			if(count($list) == 2){
				$_GET[$list[0]] = $list[1];
			}
		}
		
	}

	/**
	 * 生成URL
	 * @param  string $route  URL路径
	 * @param  array  $params URL参数
	 * @return string
	 */
	static public function url($route=null, $params=array()) {
		$app = APP_NAME;
		$controller = CONTROLLER_NAME;
		$action = ACTION_NAME;
		if($route){
			$route = explode('/', $route, 3);
			$routeNum = count($route);
			switch ($routeNum) {
				case 1:
					$action = $route[0];
					break;
				case 2:
					$controller = $route[0];
					$action = $route[1];
					break;
				case 3:
					$app = $route[0];
					$controller = $route[1];
					$action = $route[2];
					break;
			}
		}

		$extName = config('ROUTE.REWRITE_SUFFIX');

		if(self::$rewriteOn){
			$url = ROOT_URL;
		}else{
			$url = $_SERVER["SCRIPT_NAME"] .'/';
		}

		if($app == config('ROUTE.DEFAULT_APP') && $app == config('ROUTE.DEFAULT_CONTROLLER')  && $app == config('ROUTE.DEFAULT_ACTION') && empty($params)){
			return $url . $app . $extName;
		}

		$url .= $app .'/'. ucfirst($controller).'/'. $action;

		if(!empty($params)){
			foreach ($params as $key => $value) {
				$url .= '/' . $key . '-' . urlencode($value);
			}
		}

		return $url . $extName;
	}
}